package com.quickcancellation.crm.service.impl;

//import com.quickcancellation.crm.entity.Userinfo;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import com.quickcancellation.crm.constant.enu.LoginStatus;
import com.quickcancellation.crm.constant.enu.RegisterStatus;
import com.quickcancellation.crm.constant.interfaceConstant.CommonConstant;
import com.quickcancellation.crm.mapper.DictionaryMapper;
import com.quickcancellation.crm.mapper.UserinfoMapper;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.entity.Userinfo;
import com.quickcancellation.crm.pojo.vo.PrincipalVo;
import com.quickcancellation.crm.pojo.vo.RoleVo;
import com.quickcancellation.crm.pojo.vo.UserInfoVo;
import com.quickcancellation.crm.service.IRoleService;
import com.quickcancellation.crm.service.IUserinfoService;
import com.quickcancellation.crm.utils.CheckUtils;
import com.quickcancellation.crm.utils.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-02-22
 */
@Service
public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, Userinfo> implements IUserinfoService {

    @Resource
    private UserinfoMapper userinfoMapper;

    @Resource
    private DictionaryMapper dictionaryMapper;

    @Resource
    private IRoleService roleService;


    @Override
    public LoginStatus login(String usernumber, String password) {

        // 将密码再次md5加密

        String realPassword = MD5Util.getMD5(password);

        QueryWrapper<Userinfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("usernumber", usernumber);

        Userinfo userInfo = userinfoMapper.selectOne(queryWrapper);

        // 用户不存在
        if (null == userInfo) {
            return LoginStatus.LOGIN_USER_NO_EXIST;
        }

        // 判断用户名，密码是否相同
        if (!userInfo.getPassword().equals(realPassword)) {
            return LoginStatus.LOGIN_PASSWORD_WRONG;
        }

        String useStatus = dictionaryMapper.getDicKeyByDicVal("启用");

        // 判断是否被禁用
        if (!userInfo.getStatus().equals(useStatus)) {
            return LoginStatus.LOGIN_STATUS_FAIL;
        }

        return LoginStatus.LOGIN_SUCCESS;
    }

    @Override
    public IPage<Userinfo> selectUserInfoList(PageParamsDto<Userinfo> params) {
        MPJQueryWrapper wrapper = new MPJQueryWrapper<UserInfoVo>()
                .selectAll(UserInfoVo.class)
                .select("t.id",
                        "mobile",
                        "usernumber",
                        "username",
                        "sex",
                        "address",
                        "password",
                        "status",
                        "dic.dicVal as statusName"
                )
                .leftJoin("sys_t_dictionary dic on dic.dicKey = t.status");
        //.like("addr.tel", "1")
        //.le("a.province", "1");

        // 拼接参数
        if (null != params.getParams().getStatus() && !"-1".equals(params.getParams().getStatus())) {
            wrapper.eq("status", params.getParams().getStatus());
        }

        // 姓名模糊查询
        if (StringUtils.hasLength(params.getParams().getUsername())) {
            wrapper.like("username", params.getParams().getUsername());
        }

        // 用户名
        if (StringUtils.hasLength(params.getParams().getUsernumber())) {
            wrapper.like("usernumber", params.getParams().getUsernumber());
        }
        //性别
        if (StringUtils.hasLength(params.getParams().getSex())) {
            wrapper.eq("sex", params.getParams().getSex());
        }
        // 电话号码
        if (StringUtils.hasLength(params.getParams().getMobile())) {
            wrapper.like("mobile", params.getParams().getMobile());
        }
        // 地址
        if (StringUtils.hasLength(params.getParams().getAddress())) {
            wrapper.like("address", params.getParams().getAddress());
        }


        // 获取分页数据
        IPage listPage = userinfoMapper.selectJoinPage(new Page<>(params.getPage(), params.getLimit()), UserInfoVo.class, wrapper);

        List<UserInfoVo> records = listPage.getRecords();

        // 脱敏处理
        records.forEach(userInfoVo -> {
            userInfoVo.setPassword("");
        });


        listPage.setRecords(records);


//        System.out.println(JSONObject.toJSONString(listPage));

        return listPage;
    }

    @Override
    public Userinfo getUserInfoByUserNumber(String usernumber) {
        QueryWrapper<Userinfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("usernumber", usernumber);

        return userinfoMapper.selectOne(queryWrapper);
    }

    @Override
    public Userinfo getUserInfoByRequest(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader(CommonConstant.SA_TOKEN);

        // 获取用户信息
        String usernumber = StpUtil.getLoginIdByToken(token).toString();

        return getUserInfoByUserNumber(usernumber);
    }


    @Override
    public RegisterStatus checkUserInfo(Userinfo userinfo) {
        String status = userinfo.getStatus();
        String address = userinfo.getAddress();
        String mobile = userinfo.getMobile();
        String username = userinfo.getUsername();
        String usernumber = userinfo.getUsernumber();
        String sex = userinfo.getSex();

        // 判空
        if (!CheckUtils.isAllEmpty(status, address, mobile, username, usernumber, sex)) {
            return RegisterStatus.PARAMS_NULL;
        }

        QueryWrapper<Userinfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("mobile", mobile);
        // 校验电话号码格式
        if (!CheckUtils.checkPhone(mobile)) {
            return RegisterStatus.PHONE_FORMAT;
        }

        // 手机号码是否重复
        if (userinfoMapper.exists(queryWrapper)) {
            return RegisterStatus.PHONE_EXISTS;
        }

//        queryWrapper.clear();
//        queryWrapper.eq("username",username);
//        // 用户名是否重复
//        if (userinfoMapper.exists(queryWrapper)){
//            return RegisterStatus.USERNUMBER_EXISTS;
//        }

        queryWrapper.clear();
        queryWrapper.eq("usernumber", usernumber);
        // 用户名是否重复
        if (userinfoMapper.exists(queryWrapper)) {
            return RegisterStatus.USERNUMBER_EXISTS;
        }

        // 合法
        return RegisterStatus.LEGAL;
    }

    @Override
    public boolean checkUserPassword(String userId, String password) {

        QueryWrapper<Userinfo> queryWrapper = new QueryWrapper();

        String md5Password = MD5Util.getMD5(password);

        queryWrapper.eq("id", userId);

        queryWrapper.eq("password", md5Password);

        return userinfoMapper.exists(queryWrapper);
    }

    @Override
    public boolean updatePassword(String userId, String newPassword) {
        String md5Password = MD5Util.getMD5(newPassword);

        Userinfo userinfo = new Userinfo();
        userinfo.setPassword(md5Password);


        return userinfoMapper.update(userinfo, new QueryWrapper<Userinfo>().eq("id", userId)) > 0;
    }

    @Override
    public List<PrincipalVo> getprincipalList() {
        return userinfoMapper.getprincipalList();
    }

    @Override
    public List<PrincipalVo> getPrincipalListByRole(String roleName) {
        return userinfoMapper.getprincipalListByRoleName(roleName);
    }

    @Override
    public boolean checkPermission(HttpServletRequest request, String roleName) {

        boolean checkRole = false;

        Userinfo userInfo = this.getUserInfoByRequest(request);


        List<RoleVo> roleList = roleService.getRoleVoByUsernumber(userInfo.getUsernumber());

        // 校验用户是否有权限执行这个操作
        for (RoleVo roleVo : roleList) {
            if (roleVo.getRoleName().equals(roleName)){
                checkRole = roleVo.isCheck();
                break;
            }
        }

        return checkRole;
    }
}
